# goodfeng123
from flask import Flask, jsonify, request, render_template,make_response, url_for
import requests
from flask import Flask, render_template, redirect, url_for

from flask import Flask, render_template, jsonify
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)




# 假设 Grade 模型已经在上面定义了

@app.route('/student-grades')
def student_grades():
    # 查询所有成绩记录
    grades = score.query.all()

    # 按学生学号分组统计成绩
    student_grades = {}
    for grade in grades:
        if grade.student_id in student_grades:
            student_grades[grade.student_id]['total'] += grade.score
            student_grades[grade.student_id]['count'] += 1
        else:
            student_grades[grade.student_id] = {'total': grade.score, 'count': 1}

    # 计算平均分
    for student_id, data in student_grades.items():
        data['average'] = data['total'] / data['count']

    # 将数据传递给 HTML 模板
    return render_template('student_grades.html', student_grades=student_grades)




students = [
    {'id': 1, 'name': '罗崇翔', 'gender': '男', 'age': 18,
     'id_card': '2323710113', 'phone': '12345678901', 'address': '北京'},
    {'id': 2, 'name': '李四', 'gender': '男', 'age': 19,
     'id_card': '123456780', 'phone': '12345678902', 'address': '上海'},
    {'id': 3, 'name': '王五', 'gender': '女', 'age': 20,
     'id_card': '123456781', 'phone': '12345678903', 'address': '广州'}
]
courses = [{
    'id': 1, 'name': '罗崇翔', 'teacher': '张良峰', 'age': 18,
     'week': '98', 'phone': '12345678901', 'address': '北京'
}]
scores = [{
    'student_id': 1, 'name': '罗崇翔', 'id_card': '2323710113', 'age': 18,
     'week': '99'
}]

users = {
    "user1": "password1",
    "user2": "password2"
}



# Login route
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        if username in users and users[username] == password:
            # 登录成功，重定向到用户主页
            return render_template('index.html')
        else:
            # 用户名不存在或密码错误
            return '用户名或密码错误', 401
    
    # 如果是GET请求，则渲染登录页面
    return render_template('login.html')


# Register route
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        if username in users:
            # Username already exists
            return '用户名已存在', 409
        else:
            # Add new user
            users[username] = password
            return render_template('index.html')
    
    # If GET request, just render the registration page (you would need to create this)
    return render_template('register.html')

# Change password route
@app.route('/change_password', methods=['GET', 'POST'])
def change():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        if username in users:
            # Username already exists
            return '用户名已存在', 409
        else:
            # Add new user
            users[username] = password
            return render_template('index.html')
    
    # If GET request, just render the registration page (you would need to create this)
    return render_template('change_password.html')


@app.route('/') # 获取学生信息页面
def index():
    return render_template('index.html')

@app.route('/score') # 获取成绩信息页面
def score():
    return render_template('score.html')

@app.route('/course') # 获取课程信息页面
def course():
    return render_template('course.html')

@app.route('/addStu',methods=['post']) # 添加学生信息页面
def addStu():
    stu = eval(request.data.decode('utf-8'))

    stu['id'] = int(stu['id'])
    students.append(stu)
    return 'haha'

@app.route('/courses',methods=['post']) # 添加课程信息页面
def addCourse():
    course = eval(request.data.decode('utf-8'))

    course['id'] = int(course['id'])
    courses.append(course)
    return 'haha'

@app.route('/scores',methods=['post']) # 添加成绩信息页面
def addScore():
    score = eval(request.data.decode('utf-8'))

    score['student_id'] = int(score['student_id'])
    scores.append(score)
    return 'haha'




@app.route('/delStu/<int:student_id>', methods=['DELETE'])
def delete_student(student_id):
    global students, scores  # 假设 students 和 scores 是全局变量
    student_to_delete = None
    for student in students:
        if student['id'] == student_id:
            student_to_delete = student
            break

    if student_to_delete:
        # 删除学生之前，先删除该学生的所有成绩
        scores[:] = [score for score in scores if score['student_id'] != student_id]
        students.remove(student_to_delete)
        return jsonify({'message': 'Student and associated scores deleted successfully'}), 200
    else:
        return jsonify({'message': 'Student not found'}), 404



@app.route('/scores/<int:score_id>', methods=['DELETE'])
def delete_score(score_id):
    global scores  # 假设 scores 是全局变量
    score_to_delete = None
    for score in scores:
        if score['id'] == score_id:
            score_to_delete = score
            break

    if score_to_delete:
        scores.remove(score_to_delete)
        return jsonify({'message': 'Score deleted successfully'}), 200
    else:
        return jsonify({'message': 'Score not found'}), 404



# @app.route('/delStu/<int:student_id>', methods=['DELETE'])
# def delete_student(student_id):
#     # 找到对应的学生并删除
#     global students  # 假设 students 是全局变量
#     student_to_delete = None
#     for student in students:
#         if student['id'] == student_id:
#             student_to_delete = student
#             break
   
#     if student_to_delete:
#         students.remove(student_to_delete)
#         return jsonify({'message': 'Student deleted successfully'}), 200
#     else:
#         return jsonify({'message': 'Student not found'}), 404
 

@app.route('/students/<int:course_id>', methods=['DELETE'])
def delete_course(course_id):
    # 找到对应的课程并删除
    global courses  # 假设 courses 是全局变量
    course_to_delete = None
    for course in courses:
        if course['id'] == course_id:
            course_to_delete = course
            break

    if course_to_delete:
        courses.remove(course_to_delete)
        return jsonify({'message': 'Course deleted successfully'}), 200
    else:
        return jsonify({'message': 'Course not found'}), 404

# @app.route('/scores/<int:score_id>', methods=['DELETE'])
# def delete_score(score_id):
#     # 找到对应的分数并删除
#     global scores  # 假设 scores 是全局变量
#     score_to_delete = None
#     for score in scores:
#         if score['id'] == score_id:
#             score_to_delete = score
#             break

#     if score_to_delete:
#         scores.remove(score_to_delete)
#         return jsonify({'message': 'Score deleted successfully'}), 200
#     else:
#         return jsonify({'message': 'Score not found'}), 404
@app.route('/editStu/<int:student_id>', methods=['PUT'])
def edit_student_by_id(student_id):
    # 找到要更新的学生记录
    student_to_update = next((student for student in students if student['id'] == student_id), None)
    if student_to_update is None:
        return jsonify({'message': 'Student not found'}), 404

    stu = request.get_json()

    student_to_update.update(stu)

    return jsonify({'message': 'Student edited successfully'}), 200

@app.route('/editCours/<int:course_id>', methods=['PUT'])
def edit_course_by_id(course_id):
    # 找到要更新的课程记录
    course_to_update = next((course for course in courses if course['id'] == course_id), None)
    if course_to_update is None:
        return jsonify({'message': 'Course not found'}), 404

    course_data = request.get_json()

    course_to_update.update(course_data)

    return jsonify({'message': 'Course edited successfully'}), 200

@app.route('/editScore/<int:score_id>', methods=['PUT'])
def edit_score_by_id(score_id):
    # 找到要更新的成绩记录
    score_to_update = next((score for score in scores if score['id'] == score_id), None)
    if score_to_update is None:
        return jsonify({'message': 'Score not found'}), 404

    score_data = request.get_json()

    score_to_update.update(score_data)

    return jsonify({'message': 'Score edited successfully'}), 200


@app.route('/courses') # 获取学生信息页面
def getCourses():
    return jsonify(courses)

@app.route('/scores') # 获取学生信息页面
def getScores():
    return jsonify(scores)

@app.route('/students') # 获取学生信息页面
def getStudents():
    return jsonify(students)




if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0',port=80)




app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///grades.db'
db = SQLAlchemy(app)
db.create_all()
app.run(debug=True)
